package com.kuaiditu.assistant.api;

import android.os.Handler;
import android.os.Message;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Eenie on 2017/9/5.
 * Email: eeniework@gmail.com
 * Des:
 */

public abstract class FileCallback implements Callback {
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    onBefore();
                    break;
                case 1:
                    onProgress(msg.getData().getLong("cur", 0), msg.getData().getLong("tot", 0));
                    break;
                case 2:
                    onAfter(mFile);
                    break;
            }
            return true;
        }

    });
    private File mFile;
    public FileCallback(File file) {
        mFile = file;
    }


    @Override
    public void onFailure(Call call, IOException e) {

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            long totilLen = response.body().contentLength();
            InputStream is = response.body().byteStream();
            FileOutputStream fos = new FileOutputStream(mFile);
            byte[] b = new byte[512];
            int len;
            Message beforeMsg = mHandler.obtainMessage();
            beforeMsg.what = 0;
            mHandler.sendMessage(beforeMsg);
            len = is.read(b);
            long curLen = 0;
            while (len != -1) {
                curLen = curLen + len;
                fos.write(b, 0, len);
                len = is.read(b);
                Message proMsg = mHandler.obtainMessage();
                proMsg.what = 1;
                proMsg.getData().putLong("cur", curLen);
                proMsg.getData().putLong("tot", totilLen);
                mHandler.sendMessage(proMsg);
            }
            fos.flush();
            fos.close();
            is.close();
            Message afterMsg = mHandler.obtainMessage();
            afterMsg.what = 2;
            mHandler.sendMessage(afterMsg);
        }
    }


    public abstract void onBefore();

    public abstract void onProgress(long curLen, long totLen);

    public abstract void onAfter(File file);


}
